<?php
namespace app\home\logic;
use think\Db;
use services\SmsService;
class Index extends Base{

    public $freight_order_status = ['1'=>'待处理','2'=>'已处理','3'=>'撤销'];
    public $invoice_status = ['0'=>'待运送','1'=>'运输中','2'=>'已完成'];
    private $AccountInfo = [];

    public function __construct($userInfo)
    {
        parent::__construct();
        $this->AccountInfo = $userInfo;
    }

    public function sendUserInfo($param)
    {
        $uid = $this->AccountInfo['user_id'];
        if (isset($param['gender'])) {
            $widata['gender'] = intval($param['gender']);
        }
        if (isset($param['nickName'])) {
            $widata['nickname'] = htmlspecialchars($param['nickName']);
        } else {
            $widata['nickname'] = '';
        }
        if (isset($param['country'])) {
            $widata['country'] = htmlspecialchars($param['country']);
        }
        if (isset($param['province'])) {
            $widata['province'] = htmlspecialchars($param['province']);
        }
        if (isset($param['city'])) {
            $widata['city'] = htmlspecialchars($param['city']);
        }
        if (isset($param['avatarUrl'])) {
            $widata['avatar'] = htmlspecialchars($param['avatarUrl']);
        }
        $widata['update_time'] = now_time();
        Db::startTrans();
        $update = Db::name('wx_info')->where('uid',$uid)->update($widata);
        if (!$update) {
            Db::rollback();
            $this->error_data['ErrorMsg'] = '获取个人信息失败';
            return $this->printResult($this->error_data);
        }
        $update_id = Db::name('user')->where('id',$uid)->update(['nickname'=>$widata['nickname'],'update_time'=>now_time()]);
        if (!$update) {
            Db::rollback();
            $this->error_data['ErrorMsg'] = '获取个人信息失败';
            return $this->printResult($this->error_data);
        }
        Db::commit();
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = '获取个人信息成功';
        return $this->printResult($this->error_data);
    }

    public function searchBox($box_number){
        $invoice = Db::name('invoice')->alias('i')
                ->field('i.id,i.box_number,i.status,ld.title,ld.contents,i.shipper_tel,i.receiver_tel')
                ->leftJoin('logistics_details ld','i.box_number=ld.invoice_id')
                ->where(['i.box_number'=>$box_number,'status'=>1])->order('i.id DESC,ld.id DESC')->find();
        if (!$invoice) {
            $this->error_data['ErrorMsg'] = '无该箱柜编号的运单';
            return $this->printResult($this->error_data);
        }
        $invoice['status_name'] = $this->invoice_status[$invoice['status']];
        $now_time = now_time();
        $data['uid'] = $this->AccountInfo['user_id'];
        $data['box_number'] = $box_number;
        $data['invoice_id'] = $invoice['id'];
        $data['search_time'] = $now_time;
        $data['status'] = 1;
        $user_phone = Db::name('user')->where('id',$this->AccountInfo['user_id'])->value('phone');
        if ($user_phone==$invoice['shipper_tel']) {
            $data['type'] = 1;   //发货方
        }
        if ($user_phone==$invoice['receiver_tel']) {
            $data['type'] = 2;   //提货方
        }
        $insert = Db::name('search_log')->insertGetId($data);
        if (!$insert) {
            $this->error_data['ErrorMsg'] = '查询失败';
            return $this->printResult($this->error_data);
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = '查询成功';
        $this->error_data['Data'] = $invoice;
        return $this->printResult($this->error_data);
    }

    // 我要发货
    public function sendGoods($param)
    {
        $now_time = now_time();
        try {
            $data['size_id'] = $param['size_id'];
            $data['size'] = Db::name("size")->where(['id'=>$param['size_id'],'status'=>1])->value('size');
            if (!$data['size']) {
                $this->error_data['ErrorMsg'] = '箱柜尺寸参数有误';
                return $this->printResult($this->error_data);
            }
            $data['item_type_id'] = $param['item_type_id'];
            $data['item_type'] = Db::name("item_type")->where(['id'=>$param['item_type_id'],'status'=>1])->value('name');
            if (!$data['item_type']) {
                $this->error_data['ErrorMsg'] = '物品类型参数有误';
                return $this->printResult($this->error_data);
            }
            $data['use_time'] = intval(strtotime($param['use_time']));
            if ($data['use_time']<=0) {
                $this->error_data['ErrorMsg'] = '用箱时间参数有误';
                return $this->printResult($this->error_data);
            }
            $sn = $this->generat_add(['add_date'=>date('Ymd',$now_time),'add_time'=>$now_time]);
            if(!$sn) $this->error('提交失败');
            $data['order_sn'] = create_order_no('O',$sn);
            $data['uid'] = $this->AccountInfo['user_id'];
            $data['issue'] = $param['issue'];
            $data['destination'] = $param['destination'];
            $data['status'] = 1;
            $data['create_time'] = $now_time;
            $insert = Db::name('freight_order')->insertGetId($data);
            if (!$insert) {
                $this->error_data['ErrorMsg'] = '提交失败';
                return $this->printResult($this->error_data);
            }
            $this->error_data['ErrorCode'] = 1;
            $this->error_data['ErrorMsg'] = '提交成功';
            return $this->printResult($this->error_data);
        } catch (\Exception $e) {
            $this->error_data['ErrorMsg'] = '服务器繁忙';
            return $this->printResult($this->error_data);
        }
    }

    // banner
    public function getBanner()
    {
        $banner = Db::name('banner')->where('status',1)->order('id DESC')->select();
        if (count($banner)) {
            foreach ($banner as &$value) {
                $value['photo'] = get_newpic_url($value['photo']);
            }
        }
        return $banner;
    }

    // 历史货运
    public function freightHistory($param)
    {
        $page = $param['page'];
        $length = $param['length'];
        $sql = sprintf("SELECT group_concat(box_number) as box_number_set,sign_port,user_tel,sign_date FROM 51xcx_sign_history WHERE user_tel=(SELECT phone FROM 51xcx_user WHERE id=%u LIMIT 0,1) GROUP BY sign_port,sign_date,user_tel ORDER BY sign_date DESC LIMIT %u,%u",$this->AccountInfo['user_id'],($page-1)*$length,$page*$length);
        $data = Db::name('sign_history')->query($sql);
        if (count($data)) {
            foreach ($data as &$value) {
                $value['box_number_arr'] = explode(',', $value['box_number_set']);
                $value['box_number_count'] = count($value['box_number_arr']);
            }
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = 'success';
        $this->error_data['Data'] = $data;
        return $this->printResult($this->error_data);
    }

    // 我的发货
    public function freightOrder($param)
    {
        $page = $param['page'];
        $length = $param['length'];
        $data = Db::name('freight_order')->where('uid',$this->AccountInfo['user_id'])->page($page,$length)->order('id DESC')->select();
        if ($data) {
            foreach ($data as $key => $value) {
                $data[$key]['use_time'] = date('Y-m-d H:i:s',$value['use_time']);
                $data[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
                $data[$key]['status_name'] = $this->freight_order_status[$value['status']];
            }
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = 'success';
        $this->error_data['Data'] = $data;
        return $this->printResult($this->error_data);
    }

    public function myBox($param)
    {
        $this->AccountInfo['phone'] = Db::name('user')->where('id',$this->AccountInfo['user_id'])->value('phone');
        $page = $param['page'];
        $length = $param['length'];
        $type = $param['type'];  // 1-我的发货2-我的货柜
        if ($type==1) {
            $str = 'i.shipper_tel';
        } else {
            $str = 'i.receiver_tel';
        }
        $sql = sprintf("SELECT * FROM ((SELECT i.id,i.box_number,i.status,ii.entrance_time,i.port_car_no,i.delete_user FROM `51xcx_search_log` sl LEFT JOIN `51xcx_invoice` i ON i.box_number=sl.box_number LEFT JOIN `51xcx_invoice_info` ii ON i.id=ii.invoice_id WHERE sl.uid=%u AND i.status=%u AND sl.type=%u) UNION (SELECT i.id,i.box_number,i.status,ii.entrance_time,i.port_car_no,i.delete_user FROM `51xcx_invoice` i LEFT JOIN `51xcx_invoice_info` ii ON i.id=ii.invoice_id WHERE %s=%u AND i.status=%u)) res WHERE delete_user not like '%s' ORDER BY id DESC LIMIT %u,%u",$this->AccountInfo['user_id'],$param['status'],$param['type'],$str,$this->AccountInfo['phone'],$param['status'],'%,'.$this->AccountInfo['user_id'].',%',($page-1)*$length,$length);
        $data = Db::query($sql);
        // $data = Db::name('search_log')->alias('sl')
        //         ->field('i.id,i.box_number,i.status,ii.entrance_time,i.port_car_no')
        //         ->leftJoin('invoice i','i.box_number=sl.box_number')
        //         ->leftJoin('invoice_info ii','i.id=ii.invoice_id')
        //         ->where(['sl.uid'=>$this->AccountInfo['user_id'],'i.status'=>$param['status'],'sl.type'=>$param['type']])
        //         ->page($page,$length)->order('sl.id DESC')->select();
        if (count($data)) {
            foreach ($data as &$value) {
                $value['status_name'] = $this->invoice_status[$value['status']];
                $where[] = ['port_car_no','=',$value['port_car_no']];
                if ($value['entrance_time']>0) {
                    $where[] = ['create_time','<',$value['entrance_time']];
                }
                $logistics_details = Db::name('logistics_details')->field('id,title,contents,place_name')->where($where)->order('id DESC')->find();
                $value['contents'] = '';
                if ($logistics_details) {
                    $value['contents'] = $logistics_details['place_name'];
                }
            }
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = 'success';
        $this->error_data['Data'] = $data;
        return $this->printResult($this->error_data);
    }

    public function deleteMyBox($id)
    {
        $delete_user = Db::name('invoice')->where('id',$id)->value('delete_user');
        $delete_user_arr = explode(',', $delete_user);
        if (in_array($id, $delete_user_arr)) {
            $this->error_data['ErrorMsg'] = 'fail';
            return $this->printResult($this->error_data);
        }
        $delete_user_arr = array_filter($delete_user_arr);
        array_push($delete_user_arr,$this->AccountInfo['user_id']);
        $update = Db::name('invoice')->where('id',$id)->update(['delete_user'=>','.implode(',', $delete_user_arr).',','update_time'=>now_time()]);
        if (!$update) {
            $this->error_data['ErrorMsg'] = 'fail';
            return $this->printResult($this->error_data);
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = 'success';
        return $this->printResult($this->error_data);
    }

    public function myBoxInfo($box_number)
    {
        $invoice = Db::name('invoice')->alias('i')
                ->field('i.id,i.status,i.box_number,i.port_car_no,ii.entrance_time,i.shipper_tel,i.receiver_tel')
                ->leftJoin('invoice_info ii','i.id=ii.invoice_id')
                ->where('i.box_number',$box_number)->find();
        if (!$invoice) {
            $this->error_data['ErrorCode'] = 1;
            $this->error_data['ErrorMsg'] = '无该箱柜编号的运单';
            $this->error_data['Data'] = [];
            return $this->printResult($this->error_data);
        }
        $invoice['status_name'] = $this->invoice_status[$invoice['status']];
        $where[] = ['port_car_no','=',$invoice['port_car_no']];
        if ($invoice['entrance_time']>0) {
            $where[] = ['create_time','<',$invoice['entrance_time']];
        }
        $data = Db::name('logistics_details')->where($where)->order('id DESC')->find();

        if ($data) {
            $data['create_time'] = date('m-d H:s',$data['create_time']);
            $data['points'] = $data['lng'].','.$data['lat'];
            $invoice['markers'] = [['id'=>1,'latitude'=>$data['lat'],'longitude'=>$data['lng'],'title'=>$data['place_name'],'callout'=>['content'=>$data['create_time'].' '.$data['place_name']]]];
        }

        // if (count($data)) {
        //     foreach ($data as &$value) {
        //         $value['create_time'] = date('m-d H:s',$value['create_time']);
        //         $value['points'] = $value['lng'].','.$value['lat'];
        //     }
        // }
        $search_log = Db::name('search_log')->where(['box_number'=>$box_number,'uid'=>$this->AccountInfo['user_id']])->find();
        if (!$search_log) {
            $now_time = now_time();
            $sl_data['uid'] = $this->AccountInfo['user_id'];
            $sl_data['box_number'] = $box_number;
            $sl_data['invoice_id'] = $invoice['id'];
            $sl_data['search_time'] = $now_time;
            $sl_data['status'] = 1;
            $user_phone = Db::name('user')->where('id',$this->AccountInfo['user_id'])->value('phone');
            if ($user_phone==$invoice['shipper_tel']) {
                $sl_data['type'] = 1;   //发货方
            }
            if ($user_phone==$invoice['receiver_tel']) {
                $sl_data['type'] = 2;   //提货方
            }
            $insert = Db::name('search_log')->insertGetId($sl_data);
            if (!$insert) {
                $this->error_data['ErrorMsg'] = '查询失败';
                return $this->printResult($this->error_data);
            }
        }
        $invoice['detail'] = $data;
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = 'success';
        $this->error_data['Data'] = $invoice;
        return $this->printResult($this->error_data);
    }

    public function getUserInfo()
    {
        if (!$this->AccountInfo['user_id']) {
            return [];
        }
        return Db::name('user')->alias('u')->field('u.id,u.phone,u.mail,wi.gender,wi.nickname,wi.country,wi.province,wi.city,wi.avatar,u.is_driver,u.is_operator')->leftJoin('wx_info wi','wi.uid=u.id')->where('u.id',$this->AccountInfo['user_id'])->find();
    }

    public function aboutUs()
    {
        return Db::name('about_us')->find();
    }

    // 手机验证码
    public function getVerifyCode($phone)
    {
        $msg['content'] = rand(111111,999999);
        $msg['phone'] = $phone;
        $PublicLogic = Controller('publics','logic');
        $res = $PublicLogic->sendMsg($msg);




        // $smsService = new SmsService();
        // $returnData=$smsService->send(['phone'=>$phone]);
        // if(!isset($returnData["ErrorCode"]) || $returnData["ErrorCode"]==0){
        //     $this->error_data['ErrorCode']=0;
        //     if(!isset($returnData["ErrorCode"])){
        //         $this->error_data['ErrorMsg']="发送失败";
        //     }else{
        //         $this->error_data['ErrorMsg']=$returnData["ErrorMsg"];
        //     }
        //     return $this->printResult($this->error_data); 
        // }
        // $data = $returnData['Data'];
        // $res=Db::name('message')->insert($data);
        if(!$res){
            $this->error_data['ErrorCode']=0;
            $this->error_data['ErrorMsg']="发送失败";//$returnData['ErrorMsg'];
        }else{
            $this->error_data['ErrorCode']=1;
            $this->error_data['ErrorMsg']="发送成功";
        }
        return $this->printResult($this->error_data);
    }

    // 绑定手机号
    public function bindPhone($phone,$verify)
    {
        $message = Db::name('message')->where(['phone'=>$phone,'verify'=>$verify])->order('id DESC')->find();
        if (!$message) {
            $this->error_data['ErrorMsg']="验证码不存在";
            return $this->printResult($this->error_data);
        }
        if ($message['status']==2) {
            $this->error_data['ErrorMsg']="验证码已使用";
            return $this->printResult($this->error_data);
        }
        if ($message['status']==3) {
            $this->error_data['ErrorMsg']="验证码发送失败";
            return $this->printResult($this->error_data);
        }
        if ($message['period']<now_time()) {
            $this->error_data['ErrorMsg']="验证码已失效";
            return $this->printResult($this->error_data);
        }
        if ($message['verify']!=$verify) {
            $this->error_data['ErrorMsg']="验证码错误";
            return $this->printResult($this->error_data);
        }
        Db::startTrans();
        $update = Db::name('message')->where('id',$message['id'])->update(['status'=>2,'update_time'=>now_time()]);
        if (!$update) {
            Db::rollback();
            $this->error_data['ErrorMsg']="绑定失败";
            return $this->printResult($this->error_data);
        }
        $u_update = Db::name('user')->where('id',$this->AccountInfo['user_id'])->update(['phone'=>$phone,'update_time'=>now_time()]);
        if (!$u_update) {
            Db::rollback();
            $this->error_data['ErrorMsg']="绑定失败";
            return $this->printResult($this->error_data);
        }
        Db::commit();
        $this->error_data['ErrorCode']=1;
        $this->error_data['ErrorMsg']="绑定成功";
        return $this->printResult($this->error_data);
    }

    // 绑定邮箱
    public function bindMail($mail)
    {
        $u_update = Db::name('user')->where('id',$this->AccountInfo['user_id'])->update(['mail'=>$mail,'update_time'=>now_time()]);
        if (!$u_update) {
            Db::rollback();
            $this->error_data['ErrorMsg']="绑定失败";
            return $this->printResult($this->error_data);
        }
        Db::commit();
        $this->error_data['ErrorCode']=1;
        $this->error_data['ErrorMsg']="绑定成功";
        return $this->printResult($this->error_data);
    }

    // 箱柜尺寸
    public function getBoxSize()
    {
        return Db::name('size')->where('status',1)->select();
    }

    // 物品类型
    public function getItemType()
    {
        return Db::name('item_type')->where('status',1)->select();
    }

    // 提箱任务
    public function driverTask($param)
    {
        $page = $param['page'];
        $length = $param['length'];
        $data = Db::name('crewman_task')->alias('ct')
                ->field('ct.*')
                ->leftJoin('position_box pb','pb.id=ct.position_box_id')
                ->where('ct.uid='.$this->AccountInfo['user_id'].' and ct.status in (1,2) and pb.task_time>0')
                ->page($page,$length)->order('ct.id DESC')->select();
        if (count($data)) {
            foreach ($data as &$value) {
                $value['load_car_time'] = date('Y-m-d H:i:s',$value['load_car_time']);
            }
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = 'success';
        $this->error_data['Data'] = $data;
        return $this->printResult($this->error_data);
    }   

    // 提箱任务详情
    public function driverTaskInfo($id)
    {
        $info = Db::name('crewman_task')->alias('ct')
                ->field('ct.load_car_time,ct.position_box,ct.box_number,i.shipper,i.shipper_tel,i.receiver,i.receiver_tel,i.receiver_mail,i.receive_address,i.seal_number,i.spec,i.type,i.weight,i.port_car_no,i.conveyance_company')
                ->leftJoin('invoice i','i.id=ct.invoice_id')
                ->leftJoin('invoice_info ii','i.id=ii.invoice_id')
                ->where('ct.id',$id)->find();
        if (!empty($info)) {
            $info['load_car_time'] = date('Y-m-d H:i:s',$info['load_car_time']);
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = 'success';
        $this->error_data['Data'] = $info;
        return $this->printResult($this->error_data);
    }

    // 货运需求列表
    public function freightOrderTask($input)
    {
        $map = 'fo.status =1';
        // $total = Db::name('freight_order')->alias('fo')
        //         ->leftJoin('user u','u.id=fo.uid')
        //         ->where($map)->count();
        // $limit = isset($input['length'])?$input['length']:6;
        // $filter_count = ceil($total/$limit)*$limit;
        $page = isset($input['start'])?intval($input['start']):1;
        $length = isset($input['length'])?intval($input['length']):6;
        $order = 'fo.id DESC';
        $field = 'fo.*,u.nickname,u.phone';
        $data_list = Db::name('freight_order')->alias('fo')
                ->field($field)
                ->leftJoin('user u','u.id=fo.uid')
                ->where($map)->order($order)->page($page,$length)->select();
        foreach($data_list as &$val){
            $val['use_time'] = date('Y-m-d H:i:s',$val['use_time']);
            $val['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
            $val['status_name'] = $this->freight_order_status[$val['status']];
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = 'success';
        $this->error_data['Data'] = $data_list;
        return $this->printResult($this->error_data);
    }

    // 改变货运需求状态
    public function changeStatus($param)
    {
        $freight_order = Db::name('freight_order')->where('id',$param['id'])->find();
        if (!$freight_order) {
            $this->error_data['ErrorMsg'] = '不存在该需求单';
            return $this->printResult($this->error_data);
        }
        if ($freight_order['status']!=1) {
            $this->error_data['ErrorMsg'] = '需求单状态有误';
            return $this->printResult($this->error_data);
        }
        $update = Db::name('freight_order')->where('id',$param['id'])->update(['status'=>$param['status'],'update_time'=>now_time()]);
        if (!$update) {
            $this->error_data['ErrorMsg'] = '更改状态失败';
            return $this->printResult($this->error_data);
        }
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = '操作成功';
        return $this->printResult($this->error_data);
    }

}
